package basic.JUC.print100;

import basic.JUC.FirstTrial;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @创建人 MBY381
 * @创建时间 2022/4/13 17:54
 * @描述 暂无
 */
public class ReentrantLockPrint {
    static char[] a1 = "1234567".toCharArray();
    static char[] a2 = "ABCDEFG".toCharArray();
    static Lock lock = new ReentrantLock();//锁
    static Condition t1 = lock.newCondition();//t1队列
    static Condition t2 = lock.newCondition();//t2队列

    public static void main(String[] args) {
        print();
    }
    public static void print(){
        new Thread(() ->{
        try{
            lock.lock();
            for(int i=1;i<100;i=i+2){
                Thread.sleep(20);
                FirstTrial.printThreadName();

                System.out.println(i);
                t2.signal();//唤醒t2队列中等待的线程
                t1.await();//进入t1队列自旋等待
            }
//            t1.signal();//避免有线程未被唤醒
//            t2.signal();//避免有线程未被唤醒
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    },"thread1").start();

        new Thread(() ->{
        try{
            lock.lock();
            for(int i=2;i<=100;i=i+2){
                Thread.sleep(20);
                FirstTrial.printThreadName();
                System.out.println(i);
                t1.signal();//唤醒t2队列中等待的线程
                t2.await();//进入t1队列自旋等待
            }
//            t1.signal();//避免有线程未被唤醒
//            t2.signal();//避免有线程未被唤醒
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    },"thread2").start();
}
}
